package com.ifcar.app.download;

import java.io.File;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.ifcar.app.activity.HomePage;
import com.ifcar.app.util.FileUtils;
import com.ifcar.app.util.Logger;
import com.ifcar.app.activity.R;

//异步下载内部线程类
public class AppUpdateService extends Service {
    
	private static final String UPDATEURL = "http://file.ws.126.net/3g/client/netease_newsreader_android.apk";
	
    public static final int MSG_DOWNLOAD = 1;
    public static final int MSG_ERROR = 2;
    long mTotalSize = 0;
    int mAutoid = 10000;
    FileDownloader mDownLoader = null;
    
    String title = "网易新闻";
    private NotificationManager mNotificationManager;
    private WakeLock mWakeLock;
    private WifiLock mWifiLock;
    
    private RemoteViews remoteView;
    private Notification mNotification;

    long currentTimeMillis = 0;
    private PendingIntent pIntent;
    private UpdateThread mUpdateThread;
    private int mMessageCount = 0;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Create a wake lock
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "UpdateThread");
        // Create a wifi lock
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mWifiLock = wifiManager.createWifiLock("UpdateThread");

        currentTimeMillis = System.currentTimeMillis();

        mNotification = new Notification(R.drawable.stat_download_icon, "新版本已经开始更新", currentTimeMillis);

        acquireLock();
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        mUpdateThread = new UpdateThread(this, UPDATEURL);
        mUpdateThread.start();
    }

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public void onDestroy() {
        super.onDestroy();
        releaseLock();
    }

    private void acquireLock() {
        if (mWakeLock != null)
            mWakeLock.acquire();
        if (mWifiLock != null)
            mWifiLock.acquire();
    }

    private void releaseLock() {
        if (mWifiLock != null && mWifiLock.isHeld()) {
            Logger.i("TThread releaseLock mWifiLock");
            mWifiLock.release();
        }
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
        }
    }

    private void setNotification(int layoutId, int notifyId, String desc, int flags) {
        remoteView = new RemoteViews(getPackageName(), layoutId);

        mNotification.icon = notifyId;
        mNotification.contentView = remoteView;
        mNotification.contentIntent = pIntent;
        mNotification.flags = flags;

    }

    public String getFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public class UpdateThread extends Thread {
        
    	private String mDir;
    	private String mSaveFile;
        private String mUrl;
        private Context mContext;
        
        public UpdateThread(Context context, String url) {
            mUrl = url;
            mSaveFile = getFileName(url);
            mContext = context;
            mDir = FileUtils.FileTempDir;
            
            Uri uri = Uri.parse("file://" + mDir + mSaveFile);
            File f = new File(uri.getPath());
            FileUtils.deleteFile(f);
        }
        
        public void run() {
        	
        	if (null != mUrl) {
        		
                mDownLoader = new FileDownloader(mContext, mUrl, mDir, mSaveFile, 1);

                try {

                    if (mDownLoader.initStatus()) {

                        mDownLoader.download(new DownloadProgressListener() {
                        	
                            public void onDownloadSize(long size) {
                            	
                            	DownloadBean bean = new DownloadBean();
                            	
                            	bean.mLength = mDownLoader.getFileSize();
                            	bean.mDownloadSize = size;
                            	bean.mAutoid = mAutoid;
                            	bean.mTitle = title;
                            	
                                Message msg = new Message();
                                msg.what = MSG_DOWNLOAD;
                                msg.obj = bean;
                                UIHandler.sendMessage(msg);
                            }

                            @Override
                            public void onErrorListener(String ex) {
                                UIHandler.sendEmptyMessage(MSG_ERROR);
                            }
                        });

                    } else {
                        UIHandler.sendEmptyMessage(MSG_ERROR);
                    }
                } catch (Exception e) {
                    UIHandler.sendEmptyMessage(MSG_ERROR);
                }
            }
            stopSelf();
        }

        private Handler UIHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {

                super.handleMessage(msg);
                switch (msg.what) {

                case MSG_DOWNLOAD:
                    
                	DownloadBean bean = (DownloadBean) msg.obj;
                    Long percent = bean.mDownloadSize * 100 / bean.mLength;
                    
                    String percenttext = percent + "%(" + getSoftwareSize(bean.mDownloadSize) + "/" + getSoftwareSize(bean.mLength) + ")";
                    
                    String title = bean.mTitle;
                    int autoid = bean.mAutoid;
                    
                    if (percent >= 100) {

                        Intent i = new Intent(Intent.ACTION_VIEW);
                        String filePath = FileUtils.FileTempDir + getFileName(mUrl);
                        i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
                        i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        pIntent = PendingIntent.getActivity(mContext, 0, i, 0);
                        setNotification(R.layout.download_finish_notify, R.drawable.stat_download_icon, "下载已完成,点击进行安装", Notification.FLAG_AUTO_CANCEL);
                        
                        remoteView.setTextViewText(R.id.download_finish_notify_title, title);
                        remoteView.setTextViewText(R.id.download_finish_notify_percenttext, percenttext);
                        remoteView.setTextViewText(R.id.download_finish_notify_text, "下载已完成,点击进行安装");
                        mNotificationManager.notify(autoid, mNotification);
                        Toast.makeText(mContext, "\"" + title + "\"" + "下载完成", Toast.LENGTH_SHORT).show();
                    } else if(mMessageCount %5 == 0){
                        Intent i = new Intent(mContext, HomePage.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        
                        pIntent = PendingIntent.getActivity(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
                        setNotification(R.layout.download_notify, R.drawable.stat_download, "已经添加到下载列表", Notification.FLAG_ONGOING_EVENT);
                        remoteView.setProgressBar(R.id.download_notify_pb, 100, percent.intValue(), false);
                        
                        remoteView.setTextViewText(R.id.download_notify_title, title);
                        remoteView.setTextViewText(R.id.download_notify_percenttext, percenttext);

                        mNotificationManager.notify(autoid, mNotification);
                    }
                    mMessageCount ++;
                    break;
              
                case MSG_ERROR:
                    Toast.makeText(mContext, "抱歉，下载错误", Toast.LENGTH_SHORT).show();
                    break;

                }
            }
        };
        
    }
    
    private String getSoftwareSize(long size){
    	
    	String rst = "0.00M";
		
    	if(size<1024*1024){
    		rst = ""+(size/1024)+"K";
		}else{
			String temp = ""+size%1048576;
			if(temp.length()>2){
				temp = temp.substring(0, 2);
			}
			rst = ""+(size/1048576)+"."+temp+"M";
		}
			
    	return rst;
		
    }
    
    class DownloadBean{
    	public long mLength;
    	public long mDownloadSize;
    	public int mAutoid;
    	public String mTitle;
    }
}
